<template>
<a-card>

    <div  class="!mb-20">
        <a-button type="primary">插入一条数据</a-button>
     
    </div>
    <div style="height: 100%;width: 100%;">

    <WsChart  height="500px" :option="reactiveOption"/>
    </div>
  
</a-card>
</template>
<script setup>
import WsChart from '@/components/WsChart.vue';
import option from '@/utils/echart/influxdb/charge';
import {getInfluxData} from '@/api/influxdb.js';
import { onMounted } from 'vue';
const reactiveOption= reactive(option)
const timerId=ref();
const messages = ref([]); // 存储接收到的消息
let eventSource = null; // 用于保存 EventSource 实例
onMounted( ()=>  {

    //getData();

    //timer();

// 创建 EventSource 实例，连接到服务器端的 SSE 端点
    eventSource = new EventSource('/api/sse/connect/1');

    // 监听特定事件名 'sse-message'
    eventSource.addEventListener('sse-message', (event) => {
    console.log('收到消息:', event.data);
    // 解析消息并保存到 messages 中
    messages.value.push(event.data);
    });


    eventSource.onerror = (error) => {
        console.error('SSE 连接出错:', error);
        eventSource.close(); // 关闭连接
    };
})
onUnmounted(() => {
    if (timerId) {
        clearInterval(timerId.value);
    }
    if (eventSource) {
        eventSource.close();
      }
});
//这是一个定时
const timer= ()=> {
    timerId.value=setInterval(() => {
    getData()
    }, 1000);
}

const getData= ()=>{
    getInfluxData()
    .then(res=>{
        reactiveOption.xAxis.data = res.data.categories;
        reactiveOption.legends = res.data.legends;
        reactiveOption.series = res.data.series;
    })
  

}

</script>